<?php
/*
* @Author: your name
* @Date: 2021-07-28 13:12:12
 * @LastEditTime: 2021-12-15 17:21:26
 * @LastEditors: 李明
* @Description: In User Settings Edit
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/file/ImageController.php
*/

namespace App\Http\Controllers\file;

use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\LMReturn;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Image;
use App\Models\Order;
use Illuminate\Support\Facades\Storage;

class ImageController extends Controller
{
    /**
     * @description: 给客户绑定相关联的图片
     * @param {Request} $request
     * @return {*}
     */
    public function uploadImgFromUserApi(Request $request)
    {

        // 接参
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::tokenErr($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $record_worker_id = $tokenInfo['worker_id'];
            $user_id = $all['user_id'] ?? false;
            $worker_id = $all['worker_id'] ?? false;
            $order_id = $all['order_id'] ?? false;
            $img_type = $all['img_type'] ?? -1; //图片类型： -1未知 1身份证正2身份证反3转款凭证4合同照片   5: '银行卡正面',6: '银行卡反面',7: '其他'
            $weight = $all['weight'] ?? 100;
            $file = $all['file'] ?? false;
            if (!$file) {
                return LMReturn::Error("请上传图片", 'IC007');
            }
            // 获取上传文件的后缀
            $ext = $file->getClientOriginalExtension();
            $filename = md5(uniqid()) . "." . $ext;
            $realPath = $file->getRealPath();
            $path = 'image_hx/' . date("Ymd") . '/' . $filename; // 路径
            $exists = Storage::disk('new_ftp')->put('htdocs/' . $path, file_get_contents($realPath));
            if ($exists) {
                $url = env("FTP2_URL") . $path;
            } else {
                return LMReturn::Error('图片上传错误', 'IC005');
            }
            $title = $all['title'] ?? $this->image_type($img_type);
        } catch (\Throwable $th) {
            return LMReturn::Error("参数错误", 'IC006');
        }


        // 赋值
        try {
            $image = new Image;
            if ($order_id) {
                $image->order_id =  $order_id;
            }
            if ($user_id) {
                $image->user_id = $user_id;
            }
            if ($worker_id) {
                $image->worker_id = $worker_id;
            }
            if ($record_worker_id) {
                $image->record_worker_id = $record_worker_id;
            }
            $image->title = $title;
            $image->img_type = $img_type;
            $image->weight = $weight;
            $image->img_path = $path;
            $image->url = $url;
            $bank_img_result = '';
            $id_card_img_result = '';
            switch ($img_type) { // //图片类型： -1未知 1身份证正2身份证反3转款凭证4合同照片   5: '银行卡正面',6: '银行卡反面',7: '其他'
                case '1': // 1身份证正
                    $id_card_img_result = ImageContentController::idCardContentImage($realPath, 'front');
                    break;
                case '2': // 2身份证反
                    $id_card_back_img_result = ImageContentController::idCardContentImage($realPath, 'back');
                    break;
                case '5': // 5: '银行卡正面'
                    $bank_img_result = ImageContentController::bankCardContentImage($url);
                    break;
                default:
                    # code...
                    break;
            }
            $image->save();
            $image['bank_img_result'] = $bank_img_result ?? [];
            $image['id_card_img_result'] = $id_card_img_result ?? [];
            $image['id_card_back_img_result'] = $id_card_back_img_result ?? [];
            return LMReturn::Success($image);
        } catch (\Throwable $th) {
            return LMReturn::Error("入库时发生问题", 'IC009');
        }
    }

    public function changeImageApi(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error('token有问题，请检查');
        }
        //接收前端传递过来的值

        try {
            $all = $request->all();
            $img_id = $all['img_id'];
            $image = Image::find($img_id);
            $user_id = isset($all['user_id']) ? $all['user_id'] : false;
            $worker_id = isset($all['worker_id']) ? $all['worker_id'] : false;
            $title = isset($all['title']) ? $all['title'] : false;
            $img_type = isset($all['img_type']) ? $all['img_type'] : false;
            $weight = isset($all['weight']) ? $all['weight'] : 0;
        } catch (\Throwable $th) {
            return LMReturn::Error('传参出现错误，错误代码IC001', 'IC001');
        }
        try {
            if ($user_id) {
                $image->user_id = $user_id;
            }
            if ($worker_id) {
                $image->worker_id = $worker_id;
            }
            $image->title = $title;
            $image->weight = $weight;
            $image->img_type = $img_type;
            $image->save();
        } catch (\Throwable $th) {
            return LMReturn::Error('修改出现错误，错误代码IC002', 'IC002');
        }
        return LMReturn::Success($image);
    }
    public function selectImgListApi(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::tokenErr($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        $where = [];
        $all = $request->all();
        if (isset($all['img_id'])) {
            $where[] = ['id', $all['img_id']];
        }
        if (isset($all['user_id'])) {
            $where[] = ['user_id', $all['user_id']];
        }
        if (isset($all['worker_id'])) {
            $where[] = ['worker_id', $all['worker_id']];
        }
        if (isset($all['order_id'])) {
            $where[] = ['order_id', $all['order_id']];
        }
        if (isset($all['img_type'])) {
            $where[] = ['img_type', $all['img_type']];
        }
        if (isset($all['title'])) {
            $where[] = ["name", 'like', '%' . $all['title'] . '%'];
        }

        $pageSize = 30;
        if (isset($all['size'])) {
            $pageSize = $all['size'];
        }
        // dd($all);
        $info = json_decode(json_encode(Image::select(
            "image.id as img_id",
            "image.user_id",
            "image.worker_id",
            "image.order_id",
            "image.title",
            "image.url",
            "image.img_path",
            "image.img_type",
            "image.weight",
            "image.create_time",
            "image.update_time",
        )
            ->where($where)
            ->orderBy("image.update_time", "desc")
            ->paginate($pageSize)), true);
        return LMReturn::Success($info);
    }
    public function deleteimageApi(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::tokenErr($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        $where = [];
        $all = $request->all();
        if (isset($all['img_id'])) {
            $where[] = ['image.id', $all['img_id']];
        }
        // dd($all['img_id']);
        // dd($where);
        $info = json_decode(
            json_encode(
                Image::select(
                    "image.id as img_id",
                    "image.title",
                    "image.img_path",
                )
                    ->where($where)
                    ->orderBy('update_time', 'desc')
                    ->first()
            ),
            true
        );
        // 1 删除 文件图片
        $exists = Storage::disk('new_ftp')->delete('htdocs/' . $info['img_path']);
        // 2 删除 数据库图片
        if ($exists) {
            $exists = Image::where("id", $all['img_id'])->delete();
        }
        return LMReturn::sqlRes($exists, '删除成功', '删除失败');
    }
    /**
     * @description: 根据类型返回图片文字
     * @param {*} $type
     * @return {*}
     */
    public function image_type($type)
    {
        // 图片类型 -1未知 1身份证正 2身份证反 3转款凭证 4合同照片   5: '银行卡正面',6: '银行卡反面',7: '其他'
        switch ($type) {
            case '-1':
                return '未知';
            case '1':
                return '身份证正面';
            case '2':
                return '身份证反面';
            case '3':
                return '转款凭证';
            case '4':
                return '合同照片 ';
            case '5':
                return '银行卡正面';
            case '6':
                return '银行卡反面';
            case '7':
                return '其他';
            default:
                return '未知';
        }
    }
}
